//
//  ChainDBManager.m
//  Chain
//
//  Created by zhaosh on 2018/4/4.
//  Copyright © 2018年 zhaosh. All rights reserved.
//

#import "ChainDBManager.h"
#import "FCFileManager.h"
#import "Datetime.h"
#import "FMDB.h"
#import "NSString+replaceChar.h"
#import "FMDBHelper.h"

//文件目录常量
NSString  *const kOutCommonFileDir = @"common_file_dir";
static NSString *kCommonFileDir = @"Inbox";
NSString *const kDownloadFileDir = @"downloads";

//数据库表名常量
static NSString *kCommonFileTable = @"common_file_info";
static NSString *kSearchHistoryTable = @"search_history_info";

@implementation ChainDBManager

+(instancetype)shareClient{
    static dispatch_once_t onceToken;
    static ChainDBManager *_sharedClient = nil;
    dispatch_once(&onceToken, ^{
        _sharedClient = [ChainDBManager new];
    });
    return _sharedClient;
}

-(instancetype)init{
    if (self = [super init]) {
        
        FMDatabase *db = [FMDatabase databaseWithPath:[FMDBHelper dbPath]];
        [db open];
        //初始化数据库
        [FMDBHelper setDataBaseName:@"fxdb.sqlite"];
        //创建存储会议访谈录音文件的table
  
        NSString *creatCommonSql = [NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS %@ "
                                    "(id integer PRIMARY KEY AUTOINCREMENT,"
                                    "filename text NOT NULL,"
                                    "filepath text NOT NULL,"
                                    "filesize text NOT NULL,"
                                    "fkey text NOT NULL,"
                                    "extension text NOT NULL,"
                                    "filetype text NOT NULL,"
                                    "addtime text NOT NULL,"
                                    "uid text);",kCommonFileTable];
        
        
        //创建存储普通文件(来自分享,)的table
        [FMDBHelper createTable:creatCommonSql];
     
        NSString *creatSearchHistorySql = [NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS %@ (id integer PRIMARY KEY AUTOINCREMENT,titlename text NOT NULL,historytype text NOT NULL);",kSearchHistoryTable];
        //创建搜索历史table
        [FMDBHelper createTable:creatSearchHistorySql];
    
        DebugLog(@"%@",[FCFileManager pathForDocumentsDirectoryWithPath:@"fxdb.sqlite"]);
        
        [db close];
    }
    return self;
}

//为表添加指定字段
-(void)addColumnToTable:(NSString *)tableName ColumnName:(NSString *)column defaultValue:(NSString *)str{
    
    if ((tableName == nil) || (column == nil))
    {
        return;
    }
    FMDatabase *db = [FMDatabase databaseWithPath:[FCFileManager pathForDocumentsDirectoryWithPath:@"fxdb.sqlite"]];
    [db open];
    BOOL bExist = [db columnExists:column inTableWithName:tableName];
    
    if (!bExist) {
        NSString *sql;
        if ([str isEqualToString:@"NULL"] || !str) {
            sql = [NSString stringWithFormat:@"ALTER TABLE %@ ADD %@ text",tableName,column];
        }else{
            sql = [NSString stringWithFormat:@"ALTER TABLE %@ ADD %@ text default '%@' ",tableName,column,str];
        }
        
        
        [db executeUpdate:sql];
    }
    
    [db close];
}


-(BOOL)saveSearchHistoryWithDic:(NSDictionary *)historyInfo
{
    return [FMDBHelper insert:kSearchHistoryTable keyValues:historyInfo replace:YES];
}

#pragma mark =====资讯搜索历史
//newsHistory00
-(NSArray<ChainSearchHistoryItem *> *)fetchNewsSearchHistory{
    return [self fetchSearchHistoryInfoWithType:@"newsHistory"];
}

-(NSArray<ChainSearchHistoryItem *> *)fetchSearchHistoryInfoWithType:(NSString *)type
{
    NSArray *historyInfo = [FMDBHelper query:kSearchHistoryTable where:[NSString stringWithFormat:@"historytype = '%@' ORDER by id desc",type], nil];
    
    NSMutableArray *fileItems = [NSMutableArray new];
    for (NSDictionary *dic in historyInfo) {
        ChainSearchHistoryItem *item = [ChainSearchHistoryItem yy_modelWithDictionary:dic];
        [fileItems addObject:item];
    }
    return fileItems;
    
}

-(BOOL)deleteNewsSearchHistoryById:(NSString *)_id{
    return [self deleteSearchHistoryById:_id withType:@"newsHistory"];
}

-(BOOL)deleteAllNewsSearchHistory{
    return [self deleteSearchHistoryAllDataByType:@"newsHistory"];
}

-(BOOL)saveNewsHistoryWithTitle:(NSString *)titlename replaceOldData:(BOOL )replace{
    
    // 删除之前的搜索记录，保留新的搜索记录
    if (replace) {
        NSMutableArray * arr = [NSMutableArray arrayWithArray:[[[ChainDBManager shareClient] fetchNewsSearchHistory] mutableCopy]];
        for (ChainSearchHistoryItem * item in arr) {
            if ([item.titlename isEqualToString:titlename]) {
                [[ChainDBManager shareClient] deleteNewsSearchHistoryById:item.id_];
            }
        }
    }
    
    return [[ChainDBManager shareClient] saveNewsHistoryWithTitle:titlename];
}

-(BOOL)saveNewsHistoryWithTitle:(NSString *)titlename{
    NSDictionary *dic = @{
                          @"titlename":titlename,
                          @"historytype":@"newsHistory"
                          };
    return [self saveSearchHistoryWithDic:dic];
}
-(BOOL)deleteSearchHistoryById:(NSString *)searchId withType:(NSString *)type
{
    return [FMDBHelper remove:kSearchHistoryTable where:[NSString stringWithFormat:@"id = '%@' AND historytype = '%@'",searchId,type]];
}
-(BOOL)deleteSearchHistoryAllDataByType:(NSString *)type
{
    
    return [FMDBHelper remove:kSearchHistoryTable where:[NSString stringWithFormat:@"historytype = '%@'",type]];
}

-(BOOL)deleteVisitSearchHistoryById:(NSString *)_id{
    return [self deleteSearchHistoryById:_id withType:@"visit"];
}
-(BOOL)deleteAllVisitSearchHistory{
    return [self deleteSearchHistoryAllDataByType:@"visit"];
}

-(NSString *)getFileTypeByExtension:(NSString *)extension{
    NSString *fileType;
    extension = [extension stringByReplacingOccurrencesOfString:@"." withString:@""];
    extension = [extension lowercaseString];
    
    if ([extension isEqualToString:@"doc"]
        ||[extension isEqualToString:@"docx"]
        ||[extension isEqualToString:@"xls"]
        ||[extension isEqualToString:@"xlsx"]
        ||[extension isEqualToString:@"ppt"]
        ||[extension isEqualToString:@"pptx"]
        ||[extension isEqualToString:@"pdf"]
        ||[extension isEqualToString:@"txt"]
        ||[extension isEqualToString:@"epub"]
        ||[extension isEqualToString:@"html"]
        ||[extension isEqualToString:@"rtf"]
        ) {
        fileType = @"doc";
    }else if([extension isEqualToString:@"jpg"]
             ||[extension isEqualToString:@"jpeg"]
             ||[extension isEqualToString:@"gif"]
             ||[extension isEqualToString:@"bmp"]
             ||[extension isEqualToString:@"png"]){
        fileType = @"image";
    }else if([extension isEqualToString:@"mp3"]
             ||[extension isEqualToString:@"m4a"]
             ||[extension isEqualToString:@"mp4"]
             ||[extension isEqualToString:@"wav"]
             ||[extension isEqualToString:@"aac"]
             ||[extension isEqualToString:@"flac"]
             ||[extension isEqualToString:@"ape"]
             ){
        fileType = @"audio";
    }else{
        fileType = @"doc";
    }
    
    return fileType;
    
}

@end
